import { getAllGroupsWithOrg, fetchGroupSkill, fetchGroupWithBizscenariosID, fetchScenAgentList, fetchHumanflowById, fetchSessionSummaryList } from '../Api';
import Client from '../libs/Client';
import AgentDao from '../dao/AgentDao';
import StoreDao from '../dao/StoreDao';
import { BizscenariosAgent, GroupSkill, Scene, SessionClient } from '../interface';
import { getUnfinishedSummaryStatus } from '@/api/index';

export enum BusinessCmd {
	END_SESSION = 'end-session',
	SCREEN_SHOT = 'screen-shot',
	SCREEN_SHARE = 'screen-share',
	SCREEN_MARK = 'screen-mark',
	FACE_COMPARE = 'face-compare',
	ID_CARD_COMPARE = 'idcard-compare',
	SEND_LINK = 'send-link',
	SEND_VIDEO = 'send-video',
	RECORD_SCREEN = 'record-screen',
	START_SCREEN_SYNC = 'start-screen-sync',
	GET_GEO_LOCATION = 'get-geo-localtion',
	SCANNER_CODE = 'scanner-code',
	SEND_CARD_COLLECTION = 'send-card-collection',
	SHARED_WHITEDOARD = 'shared-whiteboard',
	SEND_VARIABLE_COLLECTION = 'send-variable-collection',
	TRANSCRIPT_OF_TESTIMONY = 'transcript-of-testimony',
	SEND_VIDEO_COLLECTION = 'send-video-collection',
	REGIONAL_SCREEN_RECORDING = 'regional-screen-recording',
	SHARED_PDF = 'shared-pdf',
	SEND_SIGN = 'send-sign',
	SEND_FORM = 'send-form',
	SEND_PDF = 'send-pdf',
	SNAPSHOT = 'snapshot',
	TRANSFER = 'transfer',
	INVITE = 'invite',
	SEND_KNOWLEDGE_BASE = 'knowledge-base',
}

class AgentController {
	public async fetchAllGroupsWithOrg() {
		try {
			const { data } = await getAllGroupsWithOrg();
			this.setAllGroupScene(data.scenList);
		} catch (error) {
			console.error('get all group with org error', error);
		}
	}

	public async fetchGroupSkill() {
		try {
			const { data } = await fetchGroupSkill();
		} catch (error) {
			console.error('get all group with org error', error);
		}
	}

	public async fetchGroupWithBizscenariosID(id: number, isTransfer: boolean = false) {
		try {
			if (!id) return;
			if (!isTransfer) {
				StoreDao.setProfiles({});
				StoreDao.setHumanflowSteps(null);
			}
			const { data } = await fetchGroupWithBizscenariosID(id);
			if (data.details && data.details.agentGroup) {
				this.setAllGroupSkill(data.details.agentGroup);
			}
			if (data.profiles && !isTransfer) {
				StoreDao.setProfiles({...data.profiles});
			}
			if (data.profiles && data.profiles.humanBizflow && !isTransfer) {
				await this.getHumanflowById(data.profiles.humanBizflow);
			}
			// 会话小结
			if (data.profiles && data.profiles.isSummaryOn === 'Y' && !isTransfer) {
				// 获取会话小结
				this.getSessionSummaryList(String(id));
			}
		} catch (error) {
			console.error('fetch group with Bizscenarios error', error);
		}
	}

	public async fetchBizscenariosAgents(scenId: string) {
		try {
			const { data } = await fetchScenAgentList(scenId);
			if (data.code === 200) {
				const list = data.data.map((item: any) => ({
					id: item.userId,
					userName: item.userName || '',
					fullName: item.fullName || '',
					status: item.currentStatus,
					isRobot: item.isRobot || false
				}));
				this.setBizscenariosAgents(list || []);
			}
		} catch (error) {
			console.error('fetch bizscenarios agents with page size error', error);
		}
	}

	public getAllGroupScenes() {
		return StoreDao.getAllScenes();
	}

	public setAllGroupScene(scenes: Scene[]) {
		return StoreDao.setAllScenes(scenes);
	}

	public setAllGroupSkill(groupSkill: GroupSkill[]) {
		return StoreDao.setAllGroupSkill(groupSkill);
	}

	public getAllGroupSkill() {
		return StoreDao.getAllGroupSkill();
	}
	public getTransferHeaderOptions() {
		return StoreDao.getTransferHeaderOptions();
	}

	public getBizscenariosAgents() {
		return AgentDao.getBizscenariosAgents();
	}
	public setBizscenariosAgents(list: BizscenariosAgent[]) {
		return AgentDao.setBizscenariosAgents(list);
	}

	public sendBusiness(cmd: BusinessCmd) {
		console.log(cmd);
	}

	public setSessionClient(response: SessionClient, published: boolean = false) {
		const { fromUser, data } = response;
		const { clientId, role, isRobotStream = false, status, label } = data;
		const { name = '', customerRole = '', isRobot = false } = fromUser;
		let client = new Client({ customerRole, userName: name, isRobot: isRobotStream || isRobot, clientId, role, status: published ? 'published' : status, isTeamLeader: false });
		client.setStreamInfo({ ...client.getStreamInfo(), streamLabel: label });
		client.setVideoInfo({ ...client.getVideoInfo(), id: label });
		this.saveSessionClient(client);
		console.log('setStartVideoProgress:', client, data);
	}

	public saveSessionClient(client: Client) {
		AgentDao.setSessionClient(client);
	}

	public getSessionClientWithClientID(clientId: string) {
		return AgentDao.findSessionClientWithLabel(clientId);
	}

	public getSessionClientWithLabel(label: string) {
		return AgentDao.findSessionClientWithLabel(label);
	}

	public clearSessionClient() {
		return AgentDao.clearSessionClient();
	}

	public removeSessionClientWithLabel(label: string) {
		return AgentDao.removeSessionClientWithLabel(label);
	}

	public getProfiles() {
		return StoreDao.getProfiles();
	}

	public async getHumanflowById(id: string) {
		try {
			const { data } = await fetchHumanflowById(id);
			const steps = data.humanSteps.map((item: any, index: number) => {
				return {
					id: item.id,
					humanflowId: item.humanflowId,
					name: item.name,
					tips: item.content,
					content: item.content,
					status: item.status = index === 0 ? 'doing' : 'not-started',
					isDot: item.isDot
				}
			})
			StoreDao.setHumanflowSteps(steps);
			return data;
		} catch (error) {
			console.error('get humanflow by id error', error);
		}
	}

	public getHumanflowSteps() {
		return StoreDao.getHumanflowSteps();
	}

	public setHumanflowSteps(data: any) {
		return StoreDao.setHumanflowSteps(data);
	}

	public isSessionSummaryOn() {
		return StoreDao.getProfiles()?.isSummaryOn === 'Y';
	}

	public async getSessionSummaryList(sceneId: string) {
		try {
			const { data } = await fetchSessionSummaryList(sceneId);
			console.log('fetch session summary list:', data);
			
			const list = data.data.map((item: any) => {
				return {
					id: item.id,
					name: item.name,
					type: item.type,
					data: item.data,
					isRequired: item.isRequired,
					value: item.value || ''
				}
			})
			StoreDao.setSessionSummaryList(list);
		} catch (error) {
			console.error('fetch session summary list error', error);
		}
	}

	public getSummaryList() {
		return StoreDao.getSessionSummaryList();
	}

	public async fetchUnfinishedSummaryStatus() {
		let count = 0;
		try {
			const { data } = await getUnfinishedSummaryStatus();
			if (data.code === 200) {
				count = data.data.needDoSessionSummary ? 1 : 0;
			}
		} catch (error) {
			console.error('fetch unfinished summary status error', error);
		}
		return count;
	}

	public clearProfiles() {
		StoreDao.setProfiles({});
	}

}

export default AgentController;
